package com.griddroid.serverdaemons;

import com.griddroid.configuration.GridServerConfig;
import com.griddroid.nodes.GridNode;
import com.griddroid.nodes.GridServer;
import com.griddroid.works.WorkRequest;

/**
 * This class represents Splitter daemon which is responsible to split all given 
 * {@link WorkRequest WorkRequests} into pieces. It extends the abstract class
 * {@link GridNode GridNode} to gain the main functionality of.
 * 
 * @author Charalampos Mavroforakis
 * @author Thomas Ailianos
 * @author Michail Michailidis
 */
public class SplitterDaemon extends GenericDaemon
{
	/**
	 * Constructs a SplitterDaemon and installs it into the given {@link GridServer GridServer}
	 * @param server
	 * 		server to be install in.
	 */
	public SplitterDaemon(GridServer server)
	{
		this.server = server;
	}

	/**
	 * Starts the Splitter Daemon which gets {@link WorkRequest WorkRequest} from 
	 * the {@link GridServer GridServer} and splits them into pieces called Work 
	 * Request Fragments and inserts them into the right collection of the 
	 * {@link GridServer GridServer}
	 */
	@Override
	public void run()
	{
		while (true)
		{
			while (!this.server.getWorkRequests().isEmpty())
			{
				if (this.server.getWorkerDaemon().getNumberOfWorkers() > 0)
				{
					WorkRequest temp = this.server.getWorkRequests().remove(this.server.getWorkRequests().size() - 1);
					this.server.log("Info", "ACCEPTED WORK REQUEST : " + temp.getComp().toString());
					WorkRequest[] splittedWRQs = temp.split(this.server.getWorkerDaemon().getNumberOfWorkers() * 150);
					for (WorkRequest wr : splittedWRQs)
					{
						this.server.getWorkFragmentRequests().add(wr);
					}
					this.server.log("Info", "Just splitted a work request into fragments");
				}
			}

			try
			{
				Thread.sleep(GridServerConfig.CHECKINTERVAL);
			}
			catch (InterruptedException e)
			{
			}
		}
	}
	
	/**
	 * Closes the daemon
	 */
	@Override
	public void close()
	{
	}
}
